<?php

class FarmDiscounts {
    
    public function getCategoriesAjax($params = array(), TYPO3AJAX &$ajaxObj = null) {
        $parentCategory = (t3lib_div::_GP('parent'))? intval(t3lib_div::_GP('parent')) : 0;
        $childCategories = Array();
        
        if ($parentCategory >= 0)
        {
            if ($parentCategory > 0)
            {
                //$GLOBALS['TYPO3_DB']->store_lastBuiltQuery = true;
                $res = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
                    'tx_commerce_categories.uid AS uid,
                     tx_commerce_categories.title AS title',
                    'tx_commerce_categories',
                    'tx_commerce_categories_parent_category_mm',
                    '',
                    ' AND tx_commerce_categories_parent_category_mm.uid_foreign = '.$parentCategory.' '.
                        t3lib_BEfunc::deleteClause('tx_commerce_categories')
                );
            }
            else
            {
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                    'tx_commerce_categories.uid AS uid,
                     tx_commerce_categories.title AS title',
                    'tx_commerce_categories',
                    'tx_commerce_categories.parent_category = ""'.
                        t3lib_BEfunc::deleteClause('tx_commerce_categories')
                );
            }
            
            
            if (!$GLOBALS['TYPO3_DB']->sql_error())
            {
                while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
                {
                    $childCategories[] = Array(
                        "text" => $row['title'],
                        "leaf" => false,
                        "uid" => $row['uid']
                    );
                }
                
                $GLOBALS['TYPO3_DB']->sql_free_result($res);
            }
        }
        
        $ajaxObj->setContentFormat('json');
        //$ajaxObj->addContent("sql", $GLOBALS['TYPO3_DB']->debug_lastBuiltQuery);
        $ajaxObj->setContent($childCategories);
    }
    
    /**
     *  Функция возвращает список производителей
     */
    public function getManufaturersAjax($params = array(), TYPO3AJAX &$ajaxObj = null) {
        $manufacturers = Array();
        $addWhere = '';
        
        $filter = t3lib_div::_GP('query');
		if(!$filter) {
			$manufacturers[] = Array('uid' => '', 'title' => 'Все производители');
		} else {
            $addWhere = ' AND tx_commerce_manufacturer.title LIKE ("'.$GLOBALS['TYPO3_DB']->escapeStrForLike($filter, 'tx_commerce_manufacturer').'%") ';
        }
        
        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'tx_commerce_manufacturer.uid AS uid,
             tx_commerce_manufacturer.title AS title',
            'tx_commerce_manufacturer',
            '1=1 '.$addWhere.t3lib_BEfunc::deleteClause('tx_commerce_manufacturer'),
            '',
            'tx_commerce_manufacturer.title ASC'
        );
        if (!$GLOBALS['TYPO3_DB']->sql_error()) {
            while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) $manufacturers[] = $row;
        }
        
        $ajaxObj->setContentFormat('jsonbody');
        $ajaxObj->addContent("manufacturers", $manufacturers);
    }
    
    /**
     * Функция возвращает список стран
     */
    public function getCountriesAjax($params = array(), TYPO3AJAX &$ajaxObj = null) {
        $countries = Array();
        $addWhere = '';
        
        $filter = t3lib_div::_GP('query');
		if (!$filter) {
			$countries[] = Array('uid' => '', 'title' => 'Все страны');
		} else {
			$addWhere = ' AND static_countries.cn_short_ru LIKE ("'.$GLOBALS['TYPO3_DB']->escapeStrForLike($filter, 'static_countries').'%") ';	
		}        
        
        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'static_countries.uid AS uid,
             static_countries.cn_short_ru AS title',
            'static_countries',
            '1=1 '.$addWhere.t3lib_BEfunc::deleteClause('static_countries'),
            '',
            'static_countries.cn_short_ru ASC'
        );
        if (!$GLOBALS['TYPO3_DB']->sql_error()) {
            while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) $countries[] = $row;
        }
        
        $ajaxObj->setContentFormat('jsonbody');
        $ajaxObj->addContent('countries', $countries);
    }
    
    /**
     * Функция возвращает список категорий
     */
    public function getCategoriesComboAjax($params = array(), TYPO3AJAX &$ajaxObj = null) {
        $categories = Array();
        $addWhere = '';
        
        $filter = t3lib_div::_GP('query');
		if (!$filter) {
			$categories[] = Array('uid' => '', 'title' => 'Все категории');
		} else {
			$addWhere = ' AND tx_commerce_categories.title LIKE ("'.$GLOBALS['TYPO3_DB']->escapeStrForLike($filter, 'tx_commerce_categories').'%") ';	
		}
        
        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'tx_commerce_categories.uid AS uid,
             tx_commerce_categories.title AS title',
            'tx_commerce_categories',
            '1=1 '.$addWhere.t3lib_BEfunc::deleteClause('tx_commerce_categories'),
            '',
            'tx_commerce_categories.title ASC'
        );
        if (!$GLOBALS['TYPO3_DB']->sql_error()) {
            while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) $categories[] = $row;
        }
        
        $ajaxObj->setContentFormat('jsonbody');
        $ajaxObj->addContent('categories', $categories);
    }
    
    /**
     * Функция возвращает список товаров
     */
    public function getProductsAjax($params = array(), TYPO3AJAX &$ajaxObj = null) {
        $products = Array();
        $productsCount = 0;
        $addWhere = '';
        
        $filter = Array(
            "category" => t3lib_div::_GP('category'),
            "article" => t3lib_div::_GP('article'),
            "title" => t3lib_div::_GP('title'),
            "country" => t3lib_div::_GP('country'),
            "manufacturer" => t3lib_div::_GP('manufacturer')
        );
        
        $limitStart = intval(t3lib_div::_GP('start'));
        $limitPerPage = intval(t3lib_div::_GP('limit'));
        if ($limitPerPage == 0) $limitPerPage = 20;
        
        $allowerSortOrder = Array('ASC', 'DESC');
        $sortOrder = t3lib_div::_GP('dir');
        if (!in_array($sortOrder, $allowerSortOrder)) $sortOrder = 'ASC';
        
        $sortField = t3lib_div::_GP('sort');
        switch($sortField) {
            case 'title':
                $sortField = 'tx_commerce_products.title ';
                break;
            case 'category':
                $sortField = 'tx_commerce_categories.title ';
                break;
            default:
                $sortField = 'tx_commerce_products.user_farm_commerce_article ';
                break;
        }
        
        if ($filter['article']) {
            $addWhere .= ' AND tx_commerce_products.user_farm_commerce_article LIKE ("'.$GLOBALS['TYPO3_DB']->escapeStrForLike($filter['article'], 'tx_commerce_products').'%") ';
        }
        if ($filter['title']) {
            $addWhere .= ' AND tx_commerce_products.title LIKE ("'.$GLOBALS['TYPO3_DB']->escapeStrForLike($filter['title'], 'tx_commerce_products'). '%") ';
        }
        if ($filter['manufacturer']) {
            $addWhere .= ' AND tx_commerce_products.manufacturer_uid = "'.intval($filter['manufacturer']).'" ';
        }
        if ($filter['country']) {
            $addWhere .= ' AND tx_commerce_products.user_farm_commerce_country_id = "'.intval($filter['country']).'" ';
        }
        if ($filter['category']) {
            $searchCategories = $this->getSubcategories(intval($filter['category']));
            if (count($searchCategories) > 0) {
                $addWhere .= ' AND tx_commerce_products_categories_mm.uid_foreign IN ('.implode(', ', $searchCategories).') ';
            }
            $ajaxObj->addContent('selectedCats', $searchCategories);
        }
        
        //$GLOBALS['TYPO3_DB']->store_lastBuiltQuery = true;
		$res = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
            'SQL_CALC_FOUND_ROWS 
             tx_commerce_products.uid AS uid,
			 tx_commerce_products.user_farm_commerce_article AS article,
             tx_commerce_products.title AS title,
             tx_commerce_categories.title AS category',
			'tx_commerce_products',
			'tx_commerce_products_categories_mm',
			'tx_commerce_categories',
			' AND tx_commerce_categories.deleted = 0 
              AND tx_commerce_products.deleted = 0'.$addWhere,
			'',
			$sortField.$sortOrder,
			$limitStart.', '.$limitPerPage
        );
        $ajaxObj->addContent('sql', $GLOBALS['TYPO3_DB']->debug_lastBuiltQuery);
		if (!$GLOBALS['TYPO3_DB']->sql_error()) {
			while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) $products[] = $row;
            $res = $GLOBALS['TYPO3_DB']->sql_query("SELECT FOUND_ROWS()");
            list($productsCount) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
		}
		
		$ajaxObj->setContentFormat('jsonbody');
		$ajaxObj->addContent('products', $products);
        $ajaxObj->addContent('totalRecords', $productsCount);
        
    }
    
    public function getSubcategoriesAjax($params = array(), TYPO3AJAX &$ajaxObj = null) {
		$subcategories = array();
		$parentCategory = intval(t3lib_div::_GP('parentID'));
		
		if ($parentCategory > 0) {
			$res = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
				'tx_commerce_categories.uid AS uid,
				 tx_commerce_categories.title AS title',
				'tx_commerce_categories',
				'tx_commerce_categories_parent_category_mm',
				'',
				' AND tx_commerce_categories_parent_category_mm.uid_foreign = '.$parentCategory.'
				  AND tx_commerce_categories.deleted = 0',
				'',
				'tx_commerce_categories.title ASC'
			);
		}
		
		$ajaxObj->setContentFormat('jsonbody');
		$ajaxObj->setContent($subcategories);
	}
	
	/**
     * Рекурсивно возращает список всех подкатегорий заданной категории
     */
    private function getSubcategories($categoryID) {
        $subCats = Array($categoryID);
        
        if ($categoryID > 0) {
            $res = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
                'tx_commerce_categories.uid',
                'tx_commerce_categories',
                'tx_commerce_categories_parent_category_mm',
                '',
                'tx_commerce_categories.deleted = 0 AND tx_commerce_categories_parent_category_mm.uid_foreign = '.$categoryID
            );
            
            if (!$GLOBALS['TYPO3_DB']->sql_error()) {
                while(list($curCategory) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) {
                    $curCategorySubcats = $this->getSubcategories($curCategory);
                    $subCats = array_merge($subCats, $curCategorySubcats);
                }
            }
        }
        
        return $subCats;
    }
}

if (defined("TYPO3_MODE") && $TYPO3_CONF_VARS[TYPO3_MODE]["XCLASS"]["ext/user_farm_commerce/lib/class.farmDiscounts.php"])	{
    include_once($TYPO3_CONF_VARS[TYPO3_MODE]["XCLASS"]["ext/user_farm_commerce/lib/class.farmDiscounts.php"]);
}
?>